package myjava.test;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.Iterator;

/**
 * @author Yancy
 * @program springioctest
 * @create 2021-01-15
 */
public class XmlDemo {
  public static void main(String[] args) throws DocumentException {
    // 1.创建SAXReader对象，用于读取xml文件
    SAXReader reader = new SAXReader();
    // 2.读取xml文件，得到Document对象
    Document doc =
        reader.read(
            new File("C:\\leaning_project\\springioctest\\src\\main\\resources\\score.xml"));
    // 3.获取根元素
    Element element = doc.getRootElement();
    //输出根元素
    System.out.println(element.getName()+"\n"+"------");
    // 遍历子元素
    Iterator<?> it = element.elementIterator();
    while (it.hasNext()) {
      Element e = (Element) it.next();
      System.out.println(e.getName());
      //获取id属性
        Attribute eId = e.attribute(0);
        //属性名和值
      System.out.println(eId.getName() + "="+ eId.getValue());

      //获取Student的子元素
        Element sName = e.element("name");
        Element sCourse = e.element("course");
        Element sScore = e.element("score");
      // 输出
      System.out.println(sName.getName() + "="+sName.getStringValue());
        System.out.println(sCourse.getName() + "="+sCourse.getText());
        System.out.println(sScore.getName() + "="+sScore.getText());
        System.out.println("----------");
    }
  }
}
